﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AppLimit.CloudComputing.SharpBox.StorageProvider;
using AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox;
using AppLimit.CloudComputing.SharpBox;
using System.IO;

namespace DropboxSample
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private string fileName = "LockMyPC_GUID1.txt";
        private void MainForm_Load(object sender, EventArgs e)
        {
            
        }

        CloudStorage dropBoxStorage;

        private void btnStart_Click(object sender, EventArgs e)
        {
            dropBoxStorage = new CloudStorage();
            var dropBoxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);
            // declare an access token
            ICloudStorageAccessToken accessToken = null;
            // load a valid security token from file
            using (FileStream fs = File.Open("dropboxkey.txt", FileMode.Open, FileAccess.Read, FileShare.None))
            {
                accessToken = dropBoxStorage.DeserializeSecurityToken(fs);
            }
            // open the connection 
            var storageToken = dropBoxStorage.Open(dropBoxConfig, accessToken);
            
            MessageBox.Show("App Started");
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (dropBoxStorage != null)
            {
                dropBoxStorage.Close();
            }
            
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            if (dropBoxStorage != null)
            {
                var file = dropBoxStorage.GetFile(fileName, dropBoxStorage.GetRoot());
                string tempfile = Path.Combine(Path.GetTempPath(), fileName);
                if (file != null)
                {
                    var accessor = file.GetDataTransferAccessor();
                    using (FileStream fs = new FileStream(tempfile, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        accessor.Transfer(fs, nTransferDirection.nDownload);
                    }
                }
                
                if (File.Exists(tempfile))
                {
                    File.Delete(tempfile);
                }
                using (File.Create(tempfile)) { }
                File.AppendAllText(tempfile, this.txtWrite.Text);
                dropBoxStorage.UploadFile(tempfile, dropBoxStorage.GetRoot());
            }
        }
    }
}
